package com.yc.vote.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.yc.vote.bean.Topics;
import com.yc.vote.dao.IBaseDao;
import com.yc.vote.dao.impl.BaseDaoImpl;
import com.yc.vote.service.ITopicsService;
import com.yc.vote.util.StringUtil;

public class TopicsServiceImpl implements ITopicsService{

	@Override
	public int add(Topics topics) {
		if(StringUtil.checkNull(topics.getTname(), topics.getSdate(),topics.getEdate(), topics.getUname())) {
			return -1;
		}
		
		String tid = UUID.randomUUID().toString();
		topics.setTid(tid);
		
		String[] inames = topics.getUname().split("\\$");
		topics.setUname("");
		
		List<String> sqlIds = Arrays.asList("TopicsMapper.add", "TopicItemMapper.add");
		List<Object> params = new ArrayList<Object>();
		params.add(topics);
		
		List<Object> items = new ArrayList<Object>();
		Map<String, Object> map = null;
		for(String iname : inames) {
			map = new HashMap<String, Object>();
			map.put("tid", tid);
			map.put("iname", iname);
			items.add(map);
		}
		
		params.add(items);
		IBaseDao baseDao = new BaseDaoImpl();
		
		return baseDao.update(sqlIds, params);
	}

	@Override
	public List<Topics> findAll() {
		IBaseDao baseDao = new BaseDaoImpl();
		return baseDao.list("TopicsMapper.findAll");
	}

	@Override
	public Topics findByTid(String tid) {
		if(StringUtil.checkNull(tid)) {
			return null;
		}
		IBaseDao baseDao = new BaseDaoImpl();
		return baseDao.find("TopicsMapper.findByTid", tid);
	}

	@Override
	public int update(String tid, int usid, String inos) {
		if(StringUtil.checkNull(tid, inos)) {
			return -1;
		}
		
		List<String> sqlIds = Arrays.asList("TopicsMapper.update", "TopicItemMapper.update");
		List<Object> params = new ArrayList<Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("tid", tid);
		map.put("usid", usid);
		params.add(map);
		params.add(inos.split(","));
		IBaseDao baseDao = new BaseDaoImpl();
		return baseDao.update(sqlIds, params);
	}
	
}
